<template>
  <div>
    <myDivider :name="type == 'add' || type == 'OneAdd' ? '新增审批' : '修改审批'"></myDivider>
    <el-page-header @back="$router.back(-1)">
    </el-page-header>
    <el-form ref="BigForm" :model="formData" :rules="rules" label-width="120px" style="margin-top: 50px;">

      <el-form-item label="流程设置：" prop="" required>
        <el-button size="mini" type="primary" @click="openPop">设置</el-button>
      </el-form-item>
      <!-- 显示层 -->
      <div style="display: flex;">
        <el-form-item label="应用场景：">
          <el-input disabled v-model="unitSceneText" style="width: 150px;" placeholder="请输入"></el-input>
        </el-form-item>
        <el-form-item label="单位类型：">
          <el-input disabled v-model="unitTypeText" style="width: 150px;" placeholder="请输入"></el-input>
        </el-form-item>
        <el-form-item label="单位：">
          <el-input disabled v-model="unitNames" style="width: 150px;" placeholder="请输入"></el-input>
        </el-form-item>
        <el-form-item label="部门：" v-if="popForm.applicationScenarios != 'customerRoom'">
          <el-input disabled v-model="depNames" style="width: 150px;" placeholder="请输入"></el-input>
        </el-form-item>
        <el-form-item label="审批类型：" v-if="popForm.applicationScenarios == 'customerRoom'">
          {{ typeText }}
        </el-form-item>
      </div>

      <el-form-item label="流程配置：" prop="" required>
        <div class="SWDTstyle">
          <div class="SFBtn">
            <div @click="SFBClick('big')">
              <i class="el-icon-plus"></i>
            </div>
            <div></div>
            <div @click="SFBClick('small')">
              <i class="el-icon-minus"></i>
            </div>
          </div>
          <OkrTreeByExamine v-if="OkrTreeByExamineShow" :Data="TreeData" @AddClick="AddClick" @DeleteClick="DeleteClick"
            style="transform-origin:0 0;margin: 50px 0 0 50px;" :style="{ transform: `scale(${OkrTreeSF})` }"
            ref="OkrTreeByExamine">
          </OkrTreeByExamine>
        </div>
      </el-form-item>
      <el-form-item class="btn">
        <el-button style="width: 100px;" type="primary" @click="submitForm('ruleForm')">{{ type == 'add' || type ==
          'OneAdd' ?
          '新增' : '修改' }}</el-button>
        <el-button style="width: 100px;" type="info" @click="resetForm('ruleForm')">取消</el-button>
      </el-form-item>
    </el-form>
    <!-- 审批人选择弹窗 -->
    <div class="diaBox">
      <el-dialog title="审批人选择" width="380px" :visible.sync="PopdialogTableVisible" @close="close('审批人')">
        <el-form ref="Popform" class="formStyle" :model="PopformData" :rules="Poprules" label-width="100px">
          <el-form-item label="单位：" prop="unitName">
            <el-input disabled :value="PopformData.unitName" style="width: 200px;"></el-input>
          </el-form-item>
          <el-form-item label="部门：" prop="depId">
            <el-cascader change-on-select ref="refCascader" style="width: 200px;" :props="optionProps" class="ok"
              v-model="PopformData.depId" :options="LCBuMenData" placeholder="请选择部门"
              @change="BuMenChange"></el-cascader>
          </el-form-item>
          <el-form-item label="审批人：" prop="userId">
            <el-select style="width: 200px;" v-model="PopformData.userId" placeholder="请先选择部门" @change="ShenPiChange">
              <el-option v-for="item, i in ShenPiData" :key="i" :label="item.name" :value="item.id"></el-option>
            </el-select>
          </el-form-item>
          <el-form-item class="btn">
            <el-button style="width: 100px;" type="primary" @click="PopsubmitForm">确认</el-button>
          </el-form-item>
        </el-form>
      </el-dialog>
    </div>
    <!-- 流程设置弹窗 -->
    <div class="LCSZBox">
      <el-dialog title="流程设置" :show-close="false" :close-on-click-modal="false" width="900px" :visible.sync="popShow"
        @close="close('流程设置')">
        <el-form ref="LCSZPopform" class="LCSZformStyle" :model="popForm" :rules="popRules" label-width="100px">
          <el-form-item label="应用场景：" prop="applicationScenarios">
            <el-select ref="TypeSelect" @change="typeChange" style="width: 150px;"
              v-model="popForm.applicationScenarios" placeholder="请选择应用场景">
              <el-option label="通知公告" value="notice"></el-option>
              <el-option label="新闻资讯" value="info"></el-option>
              <el-option label="入住审批" value="customerRoom"></el-option>
            </el-select>
          </el-form-item>
          <div style="display: flex;">
            <el-form-item label="单位类型：" prop="unitType">
              <el-select ref="dwlxRefs" style="width: 150px;" @change="DWLXChange"
                :disabled="userData.unitType != 'system'" v-model="popForm.unitType" placeholder="请选择应用场景">
                <el-option label="机关" value="agency"></el-option>
                <el-option label="机构" value="company"></el-option>
              </el-select>
            </el-form-item>
            <el-form-item label="单位：" prop="unitIds">
              <el-cascader :disabled="userData.unitType != 'system'" change-on-select ref="dwRefs"
                v-model="popForm.unitIds" :options="DanWeiData" @change="DanWeiChange"></el-cascader>
            </el-form-item>
            <el-form-item label="部门：" prop="depIds" v-if="popForm.applicationScenarios != 'customerRoom'">
              <el-cascader change-on-select ref="departmentRefs" @change="departmentChange" style="width: 150px;"
                v-model="popForm.depIds" :options="LCBuMenData" :props="propsss"></el-cascader>
            </el-form-item>
            <el-form-item label="审批类型：" prop="type" v-if="popForm.applicationScenarios == 'customerRoom'">
              <el-radio-group v-model="popForm.type" style="width: 220px;">
                <el-radio :label="0">按流程审批</el-radio>
                <el-radio :label="1">任意人审批</el-radio>
              </el-radio-group>
            </el-form-item>
          </div>
          <div style="display: flex;justify-content: flex-end;">
            <el-form-item>
              <el-button style="width: 100px;" type="info" @click="LCGLNoOk">取消</el-button>
              <el-button style="width: 100px;" type="primary" @click="LCGLOk">确认</el-button>
            </el-form-item>
          </div>
        </el-form>
      </el-dialog>
    </div>
  </div>
</template>

<script>
import OkrTreeByExamine from '@/components/OkrTreeByExamine'
export default {
  components: {
    OkrTreeByExamine,
  },
  data() {
    return {
      unitSceneText: '',
      unitTypeText: '',
      unitNames: '',
      depNames: '',
      typeText: '',
      propsss: {
        value: 'id',
        label: 'name',
      },

      DanWeiData: [],
      LCBuMenData: [],
      popShow: false,
      popForm: {},
      popRules: {
        applicationScenarios: [
          { required: true, message: '请选择应用场景', trigger: 'change' }
        ],
        unitType: [
          { required: true, message: '请选择单位类型', trigger: 'change' }
        ],
        unitIds: [
          { required: true, message: '请选择单位', trigger: 'change' }
        ],
        depIds: [
          { required: true, message: '请选择部门', trigger: 'change' }
        ],
        type: [
          { required: true, message: '请选择类型', trigger: 'change' }
        ]
      },
      // 使用Cascader 级联选择器后台返回的数据和要求的不一致时，做出相应改变
      optionProps: {
        value: "id",
        label: "name",
        children: "children",
      },
      type: '',
      formData: {},
      rules: {
        applicationScenarios: [
          { required: true, message: '请选择应用场景', trigger: 'change' }
        ],
      },
      OkrTreeSF: 1,
      PopdialogTableVisible: false,
      PopformData: {},
      Poprules: {
        unitName: [
          { required: true, message: '请选择应用场景', trigger: 'blur' }
        ],
        depId: [
          { required: true, message: '请选择部门', trigger: 'change' }
        ],
        userId: [
          { required: true, message: '请选择审批人', trigger: 'change' }
        ],
      },
      BuMenData: [],
      ShenPiData: [],
      userData: {},
      TreeData: [{
        name: '',
        userId: '',
        unitId: '',
        unitType: '',
        unitName: '',
        depId: '',
        depName: '添加审批人',
        id: null,
      }],
      OkrTreeByExamineShow: true,
      workUser: {},
      detpsName: [],
      TemporaryData: {}
    }
  },
  async activated() {
    this.$nextTick(() => { //清除验证
      this.$refs['BigForm'].clearValidate()
    })
    this.userData = JSON.parse(sessionStorage.getItem("logOnUser"))

    if (this.userData.unitType != 'system') { //如果是机关机构的使用自己的部门
      this.$set(this.popForm, 'unitType', this.userData.unitType)
      let dwres = await this.$api.contract.MygetOrganizationListByType(this.userData.unitType)
      this.DanWeiData = []
      dwres.data.forEach(el => {
        this.DanWeiData.push({
          label: el.name ? el.name : el.shortName,
          value: el.id
        })
      })
      this.$set(this.popForm, 'unitIds', [this.userData.unitId])
      // 获取部门列表
      let bmres = await this.$api.contract.MygetDepartmentListByOrgId(this.userData.unitType, this.userData.unitId)
      this.LCBuMenData = bmres.data
    } else {
      this.$set(this.popForm, 'unitType', '')
      this.$set(this.popForm, 'unitIds', [])
      this.DanWeiData = []
      this.LCBuMenData = []
    }
    this.$set(this.PopformData, 'unitName', this.userData.unitName)
    this.type = this.$route.query.type
    this.getDepartmentListByUnit()
    this.ShenPiData = []

    switch (this.type) {
      case 'OneAdd':
        this.popShow = true
        // 清空数据
        this.unitSceneText = ''
        this.unitTypeText = ''
        this.unitNames = ''
        this.depNames = ''
        this.typeText = ''
        this.$set(this.popForm, 'applicationScenarios', '')
        this.$set(this.popForm, 'depIds', [])
        this.$set(this.popForm, 'type', 0)
        this.$nextTick(() => {
          this.$refs['LCSZPopform'].clearValidate()
        })
        break
      case 'update':
        this.popShow = false
        // 获取详情
        let res = await this.$api.contract.detailapprovalProcess(this.$route.query.id)
        console.log(res, '详情');
        this.formData = res.data
        if (res.data.processInfo != null) {
          let arr = JSON.parse(res.data.processInfo)
          this.TreeData = arr.slice(1, arr.length - 1)
          console.log(arr, this.TreeData, 'nb');
        }
        // 获取单位列表
        let dwres = await this.$api.contract.MygetOrganizationListByType(res.data.unitType)
        this.DanWeiData = []
        dwres.data.forEach(el => {
          this.DanWeiData.push({
            label: el.name ? el.name : el.shortName,
            value: el.id
          })
        })
        // 获取部门列表
        let bmres = await this.$api.contract.MygetDepartmentListByOrgId(res.data.unitType, res.data.unitId)
        this.LCBuMenData = bmres.data

        // 流程审批弹窗 回显，this.popForm
        this.$set(this.popForm, 'applicationScenarios', res.data.applicationScenarios)
        this.$set(this.popForm, 'unitType', res.data.unitType)
        this.$set(this.popForm, 'unitIds', JSON.parse(res.data.unitIds))
        this.$set(this.popForm, 'depIds', JSON.parse(res.data.depIds))
        this.$set(this.popForm, 'type', res.data.type)


        // 基础页面第二行 应用场景四个回显
        switch (res.data.applicationScenarios) {
          case "info":
            this.unitSceneText = '新闻资讯'
            break
          case "notice":
            this.unitSceneText = '通知公告'
            break
          case "customerRoom":
            this.unitSceneText = '入住审批'
            break
        }
        switch (res.data.unitType) {
          case "agency":
            this.unitTypeText = '机关'
            break
          case "company":
            this.unitTypeText = '机构'
            break
        }
        if (res.data.unitNames) {
          this.unitNames = JSON.parse(res.data.unitNames).join('/')
        }
        if (res.data.depNames) {
          this.depNames = JSON.parse(res.data.depNames).join('/')
        }
        this.typeText = res.data.type == 0 ? '按流程审批' : '任意人审批'

        break
    }

  },
  deactivated() {
    // this.$set(this.formData, 'applicationScenarios', '')
    this.TreeData = [{
      name: '',
      userId: '',
      unitId: '',
      unitType: '',
      unitName: '',
      depId: '',
      depName: '添加审批人',
    }]

  },
  methods: {
    openPop() {
      this.popShow = true
      //存一份,如果点击取消 就恢复数据
      this.TemporaryData = {
        applicationScenarios: this.popForm.applicationScenarios,
        unitType: this.popForm.unitType,
        unitIds: this.popForm.unitIds,
        DanWeiData: this.DanWeiData,
        depIds: this.popForm.depIds,
        type: this.popForm.type,
        LCBuMenData: this.LCBuMenData,
      }
    },
    typeChange(name) {

    },
    async DWLXChange(e) { //单位类型切换

      let res = await this.$api.contract.MygetOrganizationListByType(e)
      // 清除后代选中的值
      this.DanWeiData = []
      this.$set(this.popForm, 'unitIds', [])
      this.LCBuMenData = []
      this.$set(this.popForm, 'depIds', [])
      this.$nextTick(() => {
        this.$refs['LCSZPopform'].clearValidate()
      })
      res.data.forEach(el => {
        this.DanWeiData.push({
          label: el.name ? el.name : el.shortName,
          value: el.id
        })
      })

    },
    async DanWeiChange(e) { //单位切换
      console.log(e, '单位切换事件');
      // 清除后代选中的值
      this.LCBuMenData = []
      this.$set(this.popForm, 'depIds', [])

      let res = await this.$api.contract.MygetDepartmentListByOrgId(this.popForm.unitType, e[e.length - 1])
      this.LCBuMenData = res.data
      console.log(res, '流程部门列表');
    },
    departmentChange() { //流程设置部门切换

    },
    LCGLOk() { //流程管理弹窗确认按钮
      this.$refs['LCSZPopform'].validate((valid) => {
        if (valid) {
          if (this.type == 'OneAdd') {
            this.type = 'add'
          }
          this.$set(this.popForm, 'applicationScenariosName', this.$refs['TypeSelect'].selectedLabel)
          this.$set(this.popForm, 'unitTypeName', this.$refs['dwlxRefs'].selectedLabel)
          this.$set(this.popForm, 'unitIdsName', this.$refs["dwRefs"].getCheckedNodes()[0].pathLabels.join("/"))

          if (this.popForm.applicationScenarios != 'customerRoom') {
            this.$set(this.popForm, 'depIdsName', this.$refs["departmentRefs"].getCheckedNodes()[0].pathLabels.join("/"))
            this.depNames = this.popForm.depIdsName
          }

          this.unitSceneText = this.popForm.applicationScenariosName
          this.unitTypeText = this.popForm.unitTypeName
          this.unitNames = this.popForm.unitIdsName
          this.typeText = this.popForm.type == 0 ? '按流程审批' : '任意人审批'

          this.popShow = false

          // 如果点确定的时候，只改了审批类型，则不清空审批人
          if (
            this.formData.applicationScenarios == this.popForm.applicationScenarios &&
            this.formData.unitType == this.popForm.unitType &&
            this.formData.unitIds == JSON.stringify(this.popForm.unitIds) &&
            this.formData.depIds == JSON.stringify(this.popForm.depIds)
          ) {

          } else {
            this.TreeData = [{
              name: '',
              userId: '',
              unitId: '',
              unitType: '',
              unitName: '',
              depId: '',
              depName: '添加审批人',
            }]
          }

        } else {
          console.log('error submit!!');
          return false;
        }
      });
    },
    LCGLNoOk() { //流程管理取消按钮
      if (this.type == 'OneAdd') {
        this.$router.back(-1)
      } else {
        this.$set(this.popForm, 'applicationScenarios', this.TemporaryData.applicationScenarios)
        this.$set(this.popForm, 'unitType', this.TemporaryData.unitType)
        this.$set(this.popForm, 'unitIds', this.TemporaryData.unitIds)
        this.$set(this.popForm, 'depIds', this.TemporaryData.depIds)
        this.$set(this.popForm, 'type', this.TemporaryData.type)
        this.DanWeiData = this.TemporaryData.DanWeiData
        this.LCBuMenData = this.TemporaryData.LCBuMenData
      }
      this.popShow = false
    },
    AddClick(e) { //点击添加加号的时候
      this.ShenPiData = []
      console.log(e);
      this.PopdialogTableVisible = true

      this.$set(this.PopformData, 'unitName', this.unitNames)

      this.$set(this.PopformData, 'depId', '')
      this.$set(this.PopformData, 'userId', '')
      this.$nextTick(() => { //清除验证
        this.$refs['Popform'].clearValidate()
      })
    },
    DeleteClick(e) { //删除审批人的时候
      if (this.TreeData.length == 1) {
        this.TreeData = [{
          name: '',
          userId: '',
          unitId: '',
          unitType: '',
          unitName: '',
          depId: '',
          depName: '添加审批人',
        }]
      } else {
        this.TreeData.forEach((el, i) => {
          if (el.userId == e.userId) {
            this.TreeData.splice(i, 1)
            this.OkrTreeByExamineShow = false
            setTimeout(() => {
              this.OkrTreeByExamineShow = true
            }, 200)
          }
        })
      }
      this.$message({
        message: '删除成功',
        type: 'success'
      });
    },
    PopsubmitForm() { // 新增卡片弹框的确认
      this.$refs['Popform'].validate((valid) => {
        if (valid) {
          if (this.TreeData[0].depName == '添加审批人') {
            this.TreeData = []
          }
          let Isduplicate = false;
          this.TreeData.forEach(el => {
            if (el.userId == this.workUser.id) {
              this.$message.error('已选择过该审批人，请勿重复选择')
              Isduplicate = true
            }
          })
          if (!Isduplicate) { //如果之前没添加过
            this.TreeData.push({
              name: this.workUser.name,
              userId: this.workUser.id,
              unitId: this.userData.unitId,
              unitType: this.userData.unitType,
              unitName: this.userData.unitName,
              depId: this.PopformData.depId[this.PopformData.depId.length - 1],
              depName: this.detpsName[this.detpsName.length - 1],
            })
            this.OkrTreeByExamineShow = false
            setTimeout(() => {
              this.OkrTreeByExamineShow = true
            }, 200)
          }
          this.PopdialogTableVisible = false
        } else {
          console.log('error submit!!');
          return false;
        }
      });
    },
    close(val) {
      switch (val) {
        case '流程设置':
          break
        case '审批人':
          break
      }
    },
    SFBClick(val) { //左上角的缩放和放大
      console.log(666);
      switch (val) {
        case 'big':
          if (this.OkrTreeSF > 2) return
          this.OkrTreeSF += 0.1
          break
        case 'small':
          if (this.OkrTreeSF < 0.5) return
          this.OkrTreeSF -= 0.1
          break
      }
      console.log(this.OkrTreeSF);
    },
    submitForm(formName) { //提交按钮
      this.$refs['BigForm'].validate(async (valid) => {
        if (valid) {

          if (this.TreeData.length == 1 && this.TreeData[0].depName == '添加审批人') {
            this.$message.error('请添加审批人')
            return
          }

          let arr = []
          this.TreeData.forEach(el => {
            arr.push(el)
          })
          arr.unshift({
            name: 'begin'
          })
          arr.push({
            name: 'end'
          })
          let departmentId;
          let depNames;
          let depIds;
          if (this.popForm.applicationScenarios == 'customerRoom') {
            //如果是入住审批，departmentId传0
            departmentId = 0
            depNames = ''
            depIds = JSON.stringify([])
          } else {
            departmentId = this.popForm.depIds[this.popForm.depIds.length - 1]
            depNames = JSON.stringify(this.depNames.split('/'))
            depIds = JSON.stringify(this.popForm.depIds)
          }

          switch (this.type) {
            case 'add': //新增
              let params = {
                "applicationScenarios": this.popForm.applicationScenarios,
                "processInfo": JSON.stringify(arr),
                "createUserId": this.userData.id,
                "unitType": this.popForm.unitType,
                "unitId": this.popForm.unitIds[this.popForm.unitIds.length - 1],
                "unitIds": JSON.stringify(this.popForm.unitIds),
                "unitNames": JSON.stringify(this.unitNames.split('/')),
                "departmentId": departmentId,
                "depIds": depIds,
                "depNames": depNames,
                type: this.popForm.type,
              }
              let res = await this.$api.contract.insertapprovalProcess(params)
              console.log(res, '添加结果');
              if (res.code == 200) {
                this.$message({
                  message: '添加成功',
                  type: 'success'
                })
                this.$router.back(-1)
              } else {
                this.$message.error(res.message)
              }
              break
            case 'update': //修改
              let Updateparams = {
                "id": this.$route.query.id,
                "applicationScenarios": this.popForm.applicationScenarios,
                "processInfo": JSON.stringify(arr),
                "createUserId": this.userData.id,
                "unitType": this.popForm.unitType,
                "unitId": this.popForm.unitIds[this.popForm.unitIds.length - 1],
                "unitIds": JSON.stringify(this.popForm.unitIds),
                "unitNames": JSON.stringify(this.unitNames.split('/')),
                "departmentId": departmentId,
                "depIds": depIds,
                "depNames": depNames,
                type: this.popForm.type,
              }
              let Updateres = await this.$api.contract.updateapprovalProcess(Updateparams)
              console.log(Updateres, '修改结果');
              if (Updateres.code == 200) {
                this.$message({
                  message: '修改成功',
                  type: 'success'
                })
                this.$router.back(-1)
              } else {
                this.$message.error(Updateres.message)
              }
              break
          }

        } else {
          console.log('error submit!!');
          return false;
        }
      });


    },
    resetForm(formName) { //取消按钮
      this.$router.back(-1)
    },
    ShenPiChange(value) { //审批人切换函数
      this.ShenPiData.forEach(el => {
        if (el.id == value) {
          this.workUser = el
        }
      })

      console.log('选中的工人', this.workUser);
    },
    async BuMenChange(e) { //部门切换函数
      this.ShenPiData = []//清空审核人数据
      let res = await this.$api.contract.getUserListByUnit(e[e.length - 1])
      this.ShenPiData = res.data
      this.$set(this.PopformData, 'userId', '') //清空审核人
      // 获取部门的文字
      const areaTextArr = [];
      const arr = this.$refs["refCascader"].getCheckedNodes()[0].pathNodes;
      arr.forEach((i) => {
        areaTextArr.push(i.label);
      });
      this.detpsName = areaTextArr
    },
    async getDepartmentListByUnit() { //获取部门列表
      let res = await this.$api.contract.getDepartmentListByUnit({
        name: '',
        "unitType": this.userData.unitType, //必填 单位类型 机关:agency 机构:company
        "unitId": this.userData.unitId //对应的机关机构id
      })
      if (res.code == 200) {
        this.BuMenData = this.getTreeData(res.data)
      }

    },
    // 递归
    getTreeData(data) {
      if (data == undefined) return
      for (let i = 0; i < data.length; i++) {
        if (!data[i].children) {
          // 最后一级没有数据将children变成undefined
          // data[i].children = null;
        } else {
          // children不为空时继续调用该方法
          this.getTreeData(data[i].children);
        }
      }
      return data;
    },
  },
}
</script>

<style lang="less" scoped>
.diaBox {
  position: relative;

  .formStyle {
    height: 240px;
  }

  .el-form {

    .el-form-item {
      margin-bottom: 20px;
    }
  }

  .btn {
    position: absolute;
    right: 20px;
    bottom: 20px;
  }
}

.SWDTstyle {
  width: 850px;
  height: 300px;
  background-color: #fbfbfb;
  border: 1px solid #dad9d9;
  overflow: scroll;
  position: relative;

  &::-webkit-scrollbar {
    width: 10px;
    height: 10px;
  }

  &::-webkit-scrollbar-track {
    background-color: transparent !important;
  }

  &::-webkit-scrollbar-thumb {
    background-color: rgb(169, 169, 169) !important;
    border-radius: 20000px;
  }

  .SFBtn {
    position: sticky;
    top: 5px;
    left: 5px;
    width: 84px;
    height: 35px;
    border: 1px solid darkgrey;
    border-radius: 5px;
    display: flex;
    justify-content: space-between;
    z-index: 1000;
    overflow: hidden;

    div {
      background-color: white;

      &:nth-child(1) {
        width: 41px;
        display: flex;
        justify-content: center;
        align-items: center;
      }

      &:nth-child(2) {
        width: 2px;
        height: 100%;
        background-color: darkgrey;
      }

      &:nth-child(3) {
        width: 41px;
        display: flex;
        justify-content: center;
        align-items: center;
      }
    }
  }
}

.btn {
  position: fixed;
  bottom: 10px;
  right: 70px;
}
</style>